# GF_PY3_CLASS_Minimalism_AES_ECB.py
# Create by GF 2025-04-16 20:34

class Minimalism_AES_ECB(object):

    def Encrypt(self, plaintext: str, key: str) -> str:

        # 极简 AES-ECB 加密 (仅限 ASCII 字符串, 无填充, 无完整轮函数)
        # 警告: 此实现省略了密钥扩展、列混淆、完整轮数等关键步骤, 仅用于教学演示!
        #
        # Example:
        # >>> key = "my_16_bytes_key."
        # >>> plaintext = "hello_aes_ecb"
        # >>> decrypted = M_AES_ECB = Minimalism_AES_ECB()
        # >>> encrypted = M_AES_ECB.Encrypt(plaintext, key)
        # >>> print(encrypted)
        # '051c335d5900031c073a163c0965792e'

        # 将输入转换为字节 (仅处理 ASCII)
        data_bytes = plaintext.encode('ascii')
        key_bytes = key.encode('ascii')[:16].ljust(16, b'\0') # 强制 16 字节密钥

        encrypted = bytearray()
        for i in range(0, len(data_bytes), 16):
            block = data_bytes[i:(i + 16)].ljust(16, b'\0') # 简单补零 (应使用 PKCS7 填充)

            # 模拟单轮加密 (真实 AES 有 10+ 轮)
            for d, k in zip(block, key_bytes):
                encrypted.append(d ^ k) # 仅用 XOR 模拟加密 (远非真实 AES)

        return encrypted.hex() # 返回十六进制字符串

    def Decrypt(self, ciphertext_hex: str, key: str) -> str:

        # 极简 AES-ECB 解密
        # 警告: 此实现省略了密钥扩展、列混淆、完整轮数等关键步骤, 仅用于教学演示!
        #
        # Example:
        # >>> key = "my_16_bytes_key."
        # >>> encrypted = "051c335d5900031c073a163c0965792e"
        # >>> decrypted = M_AES_ECB = Minimalism_AES_ECB()
        # >>> decrypted = M_AES_ECB.Decrypt(encrypted, key)
        # >>> print(encrypted)
        # 'hello_aes_ecb'

        encrypted_bytes = bytes.fromhex(ciphertext_hex)
        key_bytes = key.encode('ascii')[:16].ljust(16, b'\0')

        decrypted = bytearray()
        for i in range(0, len(encrypted_bytes), 16):
            block = encrypted_bytes[i:(i + 16)]

            for e, k in zip(block, key_bytes):
                decrypted.append(e ^ k) # XOR 解密

        return decrypted.decode('ascii').rstrip('\x00')

# EOF Signed by GF.
